package cn.tedu.straw.portal.service.impl;

import cn.tedu.straw.portal.dto.PostAnswerDTO;
import cn.tedu.straw.portal.ex.InsertException;
import cn.tedu.straw.portal.ex.QuestionNotFoundException;
import cn.tedu.straw.portal.mapper.AnswerMapper;
import cn.tedu.straw.portal.mapper.QuestionMapper;
import cn.tedu.straw.portal.model.Answer;
import cn.tedu.straw.portal.model.Question;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.vo.AnswerVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-10-15
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {

    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    AnswerMapper answerMapper;


    @Override
    public void post(PostAnswerDTO postAnswerDTO, Integer userId, String userNickName) {
        //获取问题的id
        Integer questionId=postAnswerDTO.getQuestionId();
        Question question=questionMapper.findById(questionId);
        if(question==null){
            throw new QuestionNotFoundException("发表答案失败!问题数据不存在，可能已被删除!");
        }

        //创建当前时间对象
        LocalDateTime now=LocalDateTime.now();
        //创建Answer对象
        Answer answer=new Answer();
        //content正文
        answer.setContent(postAnswerDTO.getContent());
        //userId
        answer.setUserId(userId);
        //userNickName
        answer.setUserNickName(userNickName);
        //问题id
        answer.setQuestionId(questionId);
        //isAccept
        answer.setIsAccepted(0);
        //当前时间
        answer.setGmtCreate(now);
        answer.setGmtModified(now);

        int rows=answerMapper.insert(answer);
        if(rows!=1){
            throw new InsertException("\"发表答案失败!服务器忙，请稍后再次尝试!");
        }

    }

    @Override
    public List<AnswerVO> getAnswerList(Integer questionId) {

        return answerMapper.findByQuestionId(questionId);

    }
}
